package com.Khan.SocialRescueSys.controller;

import com.Khan.SocialRescueSys.pojo.Force;
import com.Khan.SocialRescueSys.pojo.User;
import com.Khan.SocialRescueSys.service.ForceService;
import com.Khan.SocialRescueSys.service.ProvinceService;
import com.Khan.SocialRescueSys.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author Khan Liu
 * @date 2022/4/5 11:02
 */
@Controller
public class UploadController {

    @Autowired
    private ForceService forceService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private ProvinceService provinceService;

    public void setTypeAndProvince(Model model) {
        model.addAttribute("types", typeService.getAllType());
        model.addAttribute("provinces", provinceService.getAllProvince());
    }

    @GetMapping("/upload")
    public String toUpload(Model model){
        model.addAttribute("force",new Force());
        setTypeAndProvince(model);
        return "upload";
    }

    @PostMapping("/toUpload") //新增、编辑博客
    public String addBlog(Force force, HttpSession session, RedirectAttributes attributes){
        force.setType(typeService.getType(force.getType().getId()));
        force.setTypeId(force.getType().getId());
        force.setProvince(provinceService.getProvince(force.getProvince().getId()));
        force.setProvinceId(force.getProvince().getId());
        force.setCreateTime(new Date());
        force.setUpdateTime(new Date());
        String email = force.getEmail();
        if(!email.contains("@")){
            attributes.addFlashAttribute("msg", "邮件格式错误");
            return "redirect:/upload";
        }else{
            if(email.lastIndexOf("@") > email.lastIndexOf(".")){
                attributes.addFlashAttribute("msg", "邮件格式错误");
                return "redirect:/upload";
            }
        }
        if (force.getId() == null) {
            forceService.saveForce(force);
        }
        attributes.addFlashAttribute("msg", "新增成功");
        return "redirect:/upload";
    }
}
